package com.mipo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;


public class MongoUtil {
    	public static void main(String[] args) throws Exception {
    		/*连接到MongoDB服务 如果是远程连接可以替换localhost为服务器所在IP地址
    		两个参数分别服务器地和端口*/
    		ServerAddress serverAddress = new ServerAddress("10.82.64.35", 22017);
    		List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
    		addrs.add(serverAddress);
    		//三个参数分别用户名、数据库名、密码
    		MongoCredential credential = MongoCredential.createMongoCRCredential("JZmongo", "books", "JZmongo".toCharArray());
    		List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
    		credentials.add(credential);  
    		//通过连接认证获取MongoDB连接
    		MongoClient mongoClient = new MongoClient(addrs, credentials);
    		MongoDatabase db = mongoClient.getDatabase("books");
    		MongoCollection<Document> users = db.getCollection("units");
    		int cnt = 0;
    		for (int i =0; i< 200; i++) {
    			Thread.sleep(1000);
    			FindIterable<Document> documents = users.find().skip(i*100).limit(100);
        		for (Document document : documents) {
        			cnt++;
        			Integer level = document.getInteger("level");
        			String name = document.getString("name");
        			String code = document.getString("code");
        			String book = document.getString("book");
        			
        			ArrayList<String> list = new ArrayList<String>();
            		list.add(code);
            		Document d = new Document("children", new Document("$in", list));
            		FindIterable<Document> parent =users.find(d);
            		Document par = parent.first();
            		String parentCode = " ";
            		if (par == null) {
            			parentCode = book;
            		} else {
            			parentCode = par.getString("code");
            		}
            		
        			String str = cnt + ","+"unit"+ level + "," + code+ "," + name + "," +parentCode;
        			System.out.println(str);
        			file(str);
        			
        			
        		    //System.out.println(document);
        		}
    		}
    		mongoClient.close();
    		
		}
    	
    	
    	public static void file(String str) throws Exception{
    		String filePath = "D:/shoplist.txt";
    		File file = new File(filePath);
    		OutputStream os = new FileOutputStream(file, true);
    		os.write(str.getBytes("UTF-8"));
    		os.write("\r\n".getBytes("UTF-8"));
    		os.flush();
    		os.close();
    	}
    	
    	
    	
    	

}